package com.atcjh.advice;

import com.atcjh.exception.UserException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(UserException.class)
    @ResponseBody
    public Object customException(HttpServletRequest request, UserException e){
        System.out.println("进来了");
        System.out.println(request.getHeader("X-Requested-With"));
        //判断请求方式是否为ajax
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            return new HashMap(){{
                put("msg",e.getMessage());
            }};
        }
        //传统请求
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}
